package socket.udp.multServer;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2016/9/30 10:36
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2016/9/30 10:36
 */
public class MultUDPServer {
    private static InetSocketAddress socketAddress = null;
    private static DatagramSocket datagramSocket = null;

    public static void main(String[] args) {
        try {
            init();
            while (true) {
                byte[] buffer = new byte[1024 * 64];//缓冲区
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                datagramSocket.receive(packet);//接受数据包，会造成线程阻塞
                //receive(packet);
                new Thread(new ServerThread(datagramSocket,packet)).start();
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化连接
     */
    public static void init() {
        try {
            //创建监听地址和端口号
            socketAddress = new InetSocketAddress("localhost", 2233);
            //连接对象
            datagramSocket = new DatagramSocket(socketAddress);
            datagramSocket.setSoTimeout(5 * 1000);
            System.out.println("服务端已经启动");
        } catch (SocketException e) {
            System.out.println("服务端启动失败");
            e.printStackTrace();
        }
    }

    /**
     * 接受数据包，该方法会造成线程阻塞
     * @param packet
     * @return
     * @throws Exception
     */
    public static DatagramPacket receive(DatagramPacket packet) throws Exception{
        try {
            datagramSocket.receive(packet);
            return packet;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 将响应信息发送给请求端
     * @param packet
     */
    public static void response(DatagramPacket packet) {
        try {
            datagramSocket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

